<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
      xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
      layout:decorate="~{layout/base}">
<head>
    <title>用户管理 - 暖心助农选品平台</title>
</head>
<body>
    <div layout:fragment="content">
        <div class="d-flex justify-content-between align-items-center mb-4">
            <h3>用户管理</h3>
            <div>
                <button class="btn btn-primary me-2" data-bs-toggle="modal" data-bs-target="#addEmployeeModal">
                    <i class="fas fa-plus"></i> 添加职工
                </button>
                <button class="btn btn-success" data-bs-toggle="modal" data-bs-target="#rechargeModal">
                    <i class="fas fa-coins"></i> 职工充值
                </button>
            </div>
        </div>

        <div class="row">
            <div class="col-md-6">
                <h4>职工列表</h4>
                <div class="table-responsive">
                    <table class="table">
                        <thead>
                            <tr>
                                <th>用户名</th>
                                <th>真实姓名</th>
                                <th>余额</th>
                                <th>联系电话</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr th:each="employee : ${employees}">
                                <td th:text="${employee.username}">用户名</td>
                                <td th:text="${employee.realName}">真实姓名</td>
                                <td th:text="'￥' + ${employee.balance}">余额</td>
                                <td th:text="${employee.phone}">联系电话</td>
                                <td>
                                    <button class="btn btn-primary btn-sm" 
                                            th:data-user-id="${employee.id}"
                                            onclick="editEmployee(this.getAttribute('data-user-id'))">编辑</button>
                                    <button class="btn btn-danger btn-sm ms-1"
                                            th:data-user-id="${employee.id}"
                                            th:data-username="${employee.username}"
                                            onclick="deleteUser(this.getAttribute('data-user-id'), this.getAttribute('data-username'))">删除</button>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
            
            <div class="col-md-6">
                <h4>农户列表</h4>
                <div class="table-responsive">
                    <table class="table">
                        <thead>
                            <tr>
                                <th>用户名</th>
                                <th>真实姓名</th>
                                <th>联系电话</th>
                                <th>状态</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr th:each="farmer : ${farmers}">
                                <td th:text="${farmer.username}">用户名</td>
                                <td th:text="${farmer.realName}">真实姓名</td>
                                <td th:text="${farmer.phone}">联系电话</td>
                                <td>
                                    <span class="badge" th:classappend="${farmer.approved ? 'bg-success' : 'bg-warning'}"
                                          th:text="${farmer.approved ? '已审核' : '待审核'}">
                                        状态
                                    </span>
                                </td>
                                <td>
                                    <button class="btn btn-primary btn-sm"
                                            th:data-user-id="${farmer.id}"
                                            onclick="editFarmer(this.getAttribute('data-user-id'))">编辑</button>
                                    <button class="btn btn-danger btn-sm ms-1"
                                            th:data-user-id="${farmer.id}"
                                            th:data-username="${farmer.username}"
                                            onclick="deleteUser(this.getAttribute('data-user-id'), this.getAttribute('data-username'))">删除</button>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <!-- 添加职工模态框 -->
        <div class="modal fade" id="addEmployeeModal" tabindex="-1" aria-labelledby="addEmployeeModalLabel" aria-hidden="true">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="addEmployeeModalLabel">添加职工账号</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body">
                        <form id="addEmployeeForm" th:action="@{/admin/users/employee}" method="post">
                            <div class="mb-3">
                                <label for="username" class="form-label">用户名</label>
                                <input type="text" class="form-control" id="username" name="username" required>
                            </div>
                            
                            <div class="mb-3">
                                <label for="password" class="form-label">密码</label>
                                <input type="password" class="form-control" id="password" name="password" required>
                            </div>
                            
                            <div class="mb-3">
                                <label for="realName" class="form-label">真实姓名</label>
                                <input type="text" class="form-control" id="realName" name="realName" required>
                            </div>
                            
                            <div class="mb-3">
                                <label for="phone" class="form-label">联系电话</label>
                                <input type="tel" class="form-control" id="phone" name="phone" required>
                            </div>
                            
                            <div class="mb-3">
                                <label for="address" class="form-label">地址</label>
                                <input type="text" class="form-control" id="address" name="address" required>
                            </div>
                        </form>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                        <button type="button" class="btn btn-primary" onclick="submitAddEmployeeForm()">添加职工</button>
                    </div>
                </div>
            </div>
        </div>

        <!-- 职工充值模态框 -->
        <div class="modal fade" id="rechargeModal" tabindex="-1" aria-labelledby="rechargeModalLabel" aria-hidden="true">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="rechargeModalLabel">职工账户充值</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body">
                        <form id="rechargeForm">
                            <div class="mb-3">
                                <label for="employeeId" class="form-label">选择职工</label>
                                <select class="form-select" id="employeeId" required>
                                    <option value="">请选择职工</option>
                                    <option value="all">全部职工</option>
                                    <!-- <option th:each="employee : ${employees}"
                                            th:value="${employee.id}"
                                            th:text="${employee.realName + ' (' + employee.username + ')'}">
                                        职工名称
                                    </option> -->
                                </select>
                            </div>
                            
                            <div class="mb-3">
                                <label for="amount" class="form-label">充值金额</label>
                                <div class="input-group">
                                    <span class="input-group-text">￥</span>
                                    <input type="number" class="form-control" id="amount" value="400" 
                                           step="100" min="100" required>
                                </div>
                            </div>
                        </form>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                        <button type="button" class="btn btn-primary" onclick="submitRechargeForm()">确认充值</button>
                    </div>
                </div>
            </div>
        </div>

        <!-- 编辑用户模态框 -->
        <div class="modal fade" id="editUserModal" tabindex="-1" aria-labelledby="editUserModalLabel" aria-hidden="true">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="editUserModalLabel">编辑用户信息</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body">
                        <form id="editUserForm">
                            <input type="hidden" id="editUserId" name="id">
                            <div class="mb-3">
                                <label for="editUsername" class="form-label">用户名</label>
                                <input type="text" class="form-control" id="editUsername" name="username" readonly>
                            </div>
                            <div class="mb-3">
                                <label for="editRealName" class="form-label">真实姓名</label>
                                <input type="text" class="form-control" id="editRealName" name="realName" required>
                            </div>
                            <div class="mb-3">
                                <label for="editPhone" class="form-label">联系电话</label>
                                <input type="tel" class="form-control" id="editPhone" name="phone" required>
                            </div>
                            <div class="mb-3">
                                <label for="editAddress" class="form-label">地址</label>
                                <input type="text" class="form-control" id="editAddress" name="address" required>
                            </div>
                        </form>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                        <button type="button" class="btn btn-primary" onclick="saveUserEdit()">保存</button>
                    </div>
                </div>
            </div>
        </div>

        <!-- 删除确认模态框 -->
        <div class="modal fade" id="deleteConfirmModal" tabindex="-1" aria-labelledby="deleteConfirmModalLabel" aria-hidden="true">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="deleteConfirmModalLabel">确认删除</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body">
                        <p>确定要删除用户 "<span id="deleteUserName"></span>" 吗？</p>
                        <p class="text-danger">此操作不可恢复！</p>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                        <button type="button" class="btn btn-danger" onclick="confirmDelete()">删除</button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <th:block layout:fragment="scripts">
        <script th:inline="javascript">
            // 将模态框实例声明为全局变量
            let userModal;
            let deleteModal;
            let addEmployeeModal;
            let rechargeModal;
            let deleteUserId = null;
            
            // 确保DOM完全加载后再初始化
            document.addEventListener('DOMContentLoaded', function() {
                // 初始化所有模态框
                const modalElements = {
                    editUserModal: document.getElementById('editUserModal'),
                    deleteConfirmModal: document.getElementById('deleteConfirmModal'),
                    addEmployeeModal: document.getElementById('addEmployeeModal'),
                    rechargeModal: document.getElementById('rechargeModal')
                };

                if (modalElements.editUserModal) {
                    userModal = new bootstrap.Modal(modalElements.editUserModal);
                }
                if (modalElements.deleteConfirmModal) {
                    deleteModal = new bootstrap.Modal(modalElements.deleteConfirmModal);
                }
                if (modalElements.addEmployeeModal) {
                    addEmployeeModal = new bootstrap.Modal(modalElements.addEmployeeModal);
                }
                if (modalElements.rechargeModal) {
                    rechargeModal = new bootstrap.Modal(modalElements.rechargeModal);
                }
            });

            // 提交添加职工表单
            function submitAddEmployeeForm() {
                const form = document.getElementById('addEmployeeForm');
                const formData = new FormData(form);

                fetch(form.action, {
                    method: 'POST',
                    headers: {
                        'Accept': 'application/json'
                    },
                    body: new URLSearchParams(formData)
                })
                .then(response => {
                    if (response.redirected) {
                        // 重定向说明操作成功
                        addEmployeeModal.hide();
                        window.location.href = response.url;
                        return;
                    }
                    return response.text().then(text => {
                        if (!text) return 'success'; // 如果没有返回内容，认为是成功
                        try {
                            return JSON.parse(text);
                        } catch (e) {
                            return text;
                        }
                    });
                })
                .then(response => {
                    if (!response) return; // 如果已经重定向，这里的response会是undefined，直接返回
                    if (typeof response === 'object' && response.error) {
                        throw new Error(response.error);
                    }
                    if (response === 'success') {
                        addEmployeeModal.hide();
                        location.reload();
                    } else if (response !== undefined) { // 只在有错误响应时显示
                        console.error('Server response:', response);
                        alert('添加失败: ' + response);
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('添加失败: ' + error.message);
                });
            }

            // 提交充值表单
            function submitRechargeForm() {
                const employeeId = document.getElementById('employeeId').value;
                const amount = document.getElementById('amount').value;
                
                if (!employeeId) {
                    alert('请选择职工');
                    return;
                }

                const confirmMessage = employeeId === 'all' 
                    ? '确定要给所有职工充值 ￥' + amount + ' 吗？'
                    : '确定要给选中的职工充值 ￥' + amount + ' 吗？';
                
                if (confirm(confirmMessage)) {
                    const url = employeeId === 'all' 
                        ? /*[[@{/admin/users/recharge-all}]]*/ ''
                        : /*[[@{/admin/users}]]*/ '' + '/' + employeeId + '/recharge';

                    fetch(url, {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/x-www-form-urlencoded',
                        },
                        body: 'amount=' + encodeURIComponent(amount)
                    })
                    .then(response => response.text())
                    .then(response => {
                        if (response === 'success') {
                            rechargeModal.hide();
                            location.reload();
                        } else {
                            alert('充值失败: ' + response);
                        }
                    })
                    .catch(() => {
                        alert('充值失败');
                    });
                }
            }
            
            // 编辑职工信息
            function editEmployee(id) {
                console.log('Editing employee with ID:', id);
                
                const baseUrl = /*[[@{/admin/users}]]*/ '';
                const url = `${baseUrl}/${id}`;
                console.log('Fetching from URL:', url);
                
                fetch(url)
                    .then(response => {
                        if (!response.ok) {
                            throw new Error(`HTTP error! status: ${response.status}`);
                        }
                        return response.json();
                    })
                    .then(user => {
                        console.log('Received user data:', user);
                        if (user) {
                            // 获取所有需要的表单元素
                            const formElements = {
                                userId: document.getElementById('editUserId'),
                                username: document.getElementById('editUsername'),
                                realName: document.getElementById('editRealName'),
                                phone: document.getElementById('editPhone'),
                                address: document.getElementById('editAddress')
                            };

                            // 检查是否所有表单元素都存在
                            const missingElements = Object.entries(formElements)
                                .filter(([key, element]) => !element)
                                .map(([key]) => key);

                            if (missingElements.length > 0) {
                                throw new Error(`找不到以下表单字段：${missingElements.join(', ')}`);
                            }

                            // 设置表单值
                            formElements.userId.value = user.id;
                            formElements.username.value = user.username;
                            formElements.realName.value = user.realName;
                            formElements.phone.value = user.phone;
                            formElements.address.value = user.address;
                            
                            if (!userModal) {
                                const modalElement = document.getElementById('editUserModal');
                                if (modalElement) {
                                    userModal = new bootstrap.Modal(modalElement);
                                } else {
                                    throw new Error('找不到模态框元素');
                                }
                            }
                            userModal.show();
                        } else {
                            throw new Error('服务器返回的用户数据为空');
                        }
                    })
                    .catch(error => {
                        console.error('Error fetching user:', error);
                        alert('获取用户信息失败：' + error.message);
                    });
            }

            // 编辑农户信息
            function editFarmer(id) {
                console.log('Editing farmer with ID:', id);
                
                const baseUrl = /*[[@{/admin/users}]]*/ '';
                const url = `${baseUrl}/${id}`;
                console.log('Fetching from URL:', url);
                
                fetch(url)
                    .then(response => {
                        if (!response.ok) {
                            throw new Error(`HTTP error! status: ${response.status}`);
                        }
                        return response.json();
                    })
                    .then(user => {
                        console.log('Received user data:', user);
                        if (user) {
                            // 获取所有需要的表单元素
                            const formElements = {
                                userId: document.getElementById('editUserId'),
                                username: document.getElementById('editUsername'),
                                realName: document.getElementById('editRealName'),
                                phone: document.getElementById('editPhone'),
                                address: document.getElementById('editAddress')
                            };

                            // 检查是否所有表单元素都存在
                            const missingElements = Object.entries(formElements)
                                .filter(([key, element]) => !element)
                                .map(([key]) => key);

                            if (missingElements.length > 0) {
                                throw new Error(`找不到以下表单字段：${missingElements.join(', ')}`);
                            }

                            // 设置表单值
                            formElements.userId.value = user.id;
                            formElements.username.value = user.username;
                            formElements.realName.value = user.realName;
                            formElements.phone.value = user.phone;
                            formElements.address.value = user.address;
                            
                            if (!userModal) {
                                const modalElement = document.getElementById('editUserModal');
                                if (modalElement) {
                                    userModal = new bootstrap.Modal(modalElement);
                                } else {
                                    throw new Error('找不到模态框元素');
                                }
                            }
                            userModal.show();
                        } else {
                            throw new Error('服务器返回的用户数据为空');
                        }
                    })
                    .catch(error => {
                        console.error('Error fetching user:', error);
                        alert('获取用户信息失败：' + error.message);
                    });
            }

            // 保存用户编辑
            function saveUserEdit() {
                try {
                    // 获取所有需要的表单元素
                    const formElements = {
                        userId: document.getElementById('editUserId'),
                        realName: document.getElementById('editRealName'),
                        phone: document.getElementById('editPhone'),
                        address: document.getElementById('editAddress')
                    };

                    // 检查是否所有表单元素都存在
                    const missingElements = Object.entries(formElements)
                        .filter(([key, element]) => !element)
                        .map(([key]) => key);

                    if (missingElements.length > 0) {
                        throw new Error(`找不到以下表单字段：${missingElements.join(', ')}`);
                    }

                    const userId = formElements.userId.value;
                    const userData = {
                        realName: formElements.realName.value,
                        phone: formElements.phone.value,
                        address: formElements.address.value
                    };

                    console.log('Saving user data:', userData);
                    
                    const baseUrl = /*[[@{/admin/users}]]*/ '';
                    const url = `${baseUrl}/${userId}`;
                    console.log('Saving to URL:', url);

                    fetch(url, {
                        method: 'PUT',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify(userData)
                    })
                    .then(response => {
                        if (!response.ok) {
                            throw new Error(`HTTP error! status: ${response.status}`);
                        }
                        return response.text();
                    })
                    .then(response => {
                        console.log('Save response:', response);
                        if (response === 'success') {
                            if (userModal) {
                                userModal.hide();
                            }
                            location.reload();
                        } else {
                            throw new Error(response || '保存失败');
                        }
                    })
                    .catch(error => {
                        console.error('Error saving user:', error);
                        alert('保存失败：' + error.message);
                    });
                } catch (error) {
                    console.error('Error in saveUserEdit:', error);
                    alert('保存失败：' + error.message);
                }
            }

            // 删除用户
            function deleteUser(id, username) {
                deleteUserId = id;
                document.getElementById('deleteUserName').textContent = username;
                deleteModal.show();
            }

            // 确认删除
            function confirmDelete() {
                if (!deleteUserId) {
                    alert('删除失败：用户ID无效');
                    return;
                }

                const baseUrl = /*[[@{/admin/users}]]*/ '';
                const url = `${baseUrl}/${deleteUserId}`;
                
                fetch(url, {
                    method: 'DELETE'
                })
                .then(response => {
                    if (!response.ok) {
                        throw new Error(`HTTP error! status: ${response.status}`);
                    }
                    return response.text();
                })
                .then(response => {
                    console.log('Delete response:', response);
                    if (response === 'success') {
                        deleteModal.hide();
                        location.reload();
                    } else {
                        throw new Error(response || '删除失败');
                    }
                })
                .catch(error => {
                    console.error('Error deleting user:', error);
                    alert('删除失败：' + error.message);
                });
            }
        </script>
    </th:block>
</body>
</html> 